<template>
  <div class="page-video-data">
    <div class="left-class" :style="{ height: leftHeight + 'px' }">
      <video
        ref="videoPlayer"
        v-if="videoUrl"
        :src="videoUrl"
        controls
        class="video-class"
        @play="handlePlay"
        @pause="handlePause"
        @timeupdate="handelTimeUpdate"
        @ended="handleEnded"
        controlsList="nofullscreen"
      />
      <a-empty v-else>
        <template #description>
          <span style="color: #b2b2b2"> 暂无视频，请先添加视频 </span>
        </template>
      </a-empty>
    </div>
    <a-divider class="resizable-divider" style="border-color: #1677ff; cursor: pointer" dashed @mousedown="startResize">
      <div style="color: rgb(178, 178, 178); font-size: 12px">
        <span>↑上下拖动↓</span>
      </div>
    </a-divider>
    <div class="right-class" :style="{ height: `calc(100% - ${leftHeight + 60}px)` }">
      <div style="padding: 0 0 10px 0px; display: flex; justify-content: space-between">
        <label for="fileInput" class="custom-file-upload" @change="onVideoUpload">
          添加视频
          <input type="file" @change="onVideoUpload" accept="video/*" id="fileInput" />
        </label>
        <div style="display: flex; gap: 10px">
          <a-button @click="onCreateHeader" size="default">添加表头</a-button>
          <a-button type="dashed" @click="onCreateTag" size="default">添加标签</a-button>
          <a-tooltip placement="topLeft" title="导出Excel后可先设置合适的列宽和自动换行，以便展示完整的数据">
            <a-button type="primary" size="default" @click="onExport" @keyup="handleKeyUp">导出表格</a-button>
          </a-tooltip>
        </div>
      </div>
      <a-table
        :dataSource="dataSource"
        size="small"
        bordered
        :pagination="false"
        class="table-class"
        :scroll="{ y: `calc(100vh - ${leftHeight + 180}px` }"
        v-if="headerDataSource.length > 0"
      >
        <template #headerCell="{ column }">
          <template v-if="column.title != '操作' && column.title != '标签'">
            <span> {{ column.title }} </span>
            <DeleteOutlined
              style="color: #e21111; cursor: pointer; margin-left: 8px"
              @click="onDeleteHeader(column.key)"
            />
          </template>
        </template>
        <template #emptyText>
          <a-empty style="margin: 10px 0">
            <template #description>
              <span style="color: #b2b2b2"> 暂无标签，请添加标签 </span>
            </template>
          </a-empty>
        </template>
        <a-table-column title="标签" dataIndex="title" :width="200">
          <template #default="{ record }">
            <a-textarea
              :auto-size="{ maxRows: 5 }"
              key=""
              v-model:value="record.title"
              style="background: #313234; color: #fff"
            />
          </template>
        </a-table-column>
        <a-table-column :title="item.title" v-for="(item, index) in headerDataSource" :key="index">
          <template #default="{ record }">
            <div class="cell-header">
              <div>{{ record[item.key]?.length || "-" }}</div>
              <a-button
                type="primary"
                shape="circle"
                :icon="h(PlusOutlined)"
                size="small"
                @click="onAddAction(record, item.key)"
                @keyup="handleKeyUp"
              />
            </div>
            <div class="time-list">
              <div v-for="(item1, index) in record[item.key]" :key="index" class="time-item">
                <div>{{ convertSecondsToTime(item1) }}</div>
                <div class="item-icon">
                  <ForwardOutlined style="color: #1677ff; cursor: pointer" @click="onForward(item1)" />
                  <ScissorOutlined
                    style="color: #ffc125; cursor: pointer"
                    @click="onCut(record.title, item.title, item1)"
                  />
                  <DeleteOutlined
                    style="color: #e21111; cursor: pointer"
                    @click="onDeleteTime(record, index, item.key, item1)"
                  />
                </div>
              </div>
            </div>
          </template>
        </a-table-column>
        <a-table-column title="操作" dataIndex="operate" :width="50">
          <template #default="{ record }">
            <span style="color: #e21111; cursor: pointer" @click="onDeleteTag(record)">删除</span>
          </template>
        </a-table-column>
      </a-table>
      <div v-else style="display: flex; justify-content: center; align-items: center; height: calc(100% - 100px)">
        <a-empty>
          <template #description>
            <span style="color: #b2b2b2"> 暂无表头，请先添加表头 </span>
          </template>
        </a-empty>
      </div>
    </div>
    <TagDrawer ref="tagDrawerRef" @refresh="refreshDataSource" />
    <HeaderDrawer ref="headerDrawerRef" @refresh="refreshHeaderDataSource" />
    <VideoCutModal ref="videoCutDialogRef" />
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, onUnmounted } from "vue";
import TagDrawer from "./components/TagDrawer.vue";
import { h } from "vue";
import { PlusOutlined, ForwardOutlined, DeleteOutlined, ScissorOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import * as XLSX from "xlsx";
import dayjs from "dayjs";
import VideoCutModal from "./components/VideoCutModal.vue";
import HeaderDrawer from "./components/HeaderDrawer.vue";
export default defineComponent({
  components: {
    TagDrawer,
    PlusOutlined,
    ForwardOutlined,
    DeleteOutlined,
    ScissorOutlined,
    VideoCutModal,
    HeaderDrawer,
  },
  setup() {
    const dataProps = reactive({
      videoUrl: "" as any,
      videoFile: null as any,
      currentTime: 0 as number,
      duration: 0 as number,
      headerDataSource: [] as any,
      dataSource: [] as any,
      leftHeight: 400,
    });
    const videoPlayer = ref<HTMLVideoElement | null>(null);
    const tagDrawerRef = ref(null) as any;
    const headerDrawerRef = ref(null) as any;

    const videoCutDialogRef = ref(null) as any;

    onMounted(() => {
      window.addEventListener("keydown", handleGlobalSpacePress);
    });

    const handleGlobalSpacePress = (event: any) => {
      if (event.key === " ") {
        // 确保是空格键
        console.log("全局空格键被按下了！");
        // 在这里添加你的逻辑
        if (videoPlayer.value) {
          if (videoPlayer.value.paused) {
            videoPlayer.value.play();
          } else {
            videoPlayer.value.pause();
          }
        } else {
          console.log("视频播放器未找到");
        }
      }
    };
    onUnmounted(() => {
      window.removeEventListener("keydown", handleGlobalSpacePress);
    });

    const handleKeyUp = (event: KeyboardEvent) => {
      if (event.key === " ") {
        // 阻止默认行为，例如阻止空格键触发按钮点击
        event.preventDefault();
        event.stopPropagation(); // 阻止事件冒泡
      }
    };

    const onVideoUpload = (event: Event) => {
      const target = event.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        const file = target.files[0];
        dataProps.videoUrl = URL.createObjectURL(file);
        console.log(dataProps.videoUrl);
      }
      if (target.files && target.files[0]) {
        dataProps.videoFile = target.files[0];
        console.log(dataProps.videoFile);
      }
      // console.log("videoPlayer.value========", videoPlayer.value);
      dataProps.currentTime = videoPlayer.value?.currentTime || 0;
      dataProps.duration = videoPlayer.value?.duration || 0;
    };

    const handlePlay = (event: Event) => {
      console.log("视频开始播放", event);
      // console.log("videoPlayer.value========", videoPlayer.value);
      // 在这里添加播放开始时的业务逻辑
    };

    const handlePause = (event: Event) => {
      console.log("视频已暂停", event);
      // 可以在这里保存播放进度或更新播放状态
      // console.log("videoPlayer.value========", videoPlayer.value);
    };
    const handelTimeUpdate = (_event: Event) => {
      if (!videoPlayer.value) return;
      // console.log("当前时间:", videoPlayer.value.currentTime);
      // console.log("总时长:", videoPlayer.value.duration);
      // 适合更新进度条或记录播放位置
      // console.log("videoPlayer.value========", videoPlayer.value);
      dataProps.currentTime = videoPlayer.value.currentTime;
      dataProps.duration = videoPlayer.value.duration;
    };
    // 播放结束事件
    const handleEnded = (_event: Event) => {
      console.log("播放已完成");
      // 可以在这里显示重播按钮或播放下一个视频
      // console.log("videoPlayer.value========", videoPlayer.value);
    };

    const onCreateHeader = () => {
      console.log("添加表头");
      headerDrawerRef.value?.openDrawer("添加表头", dataProps.headerDataSource);
    };

    const refreshHeaderDataSource = (dataSource: any) => {
      console.log("刷新表头数据源", dataSource);
      dataProps.headerDataSource = dataSource;
    };

    const onCreateTag = () => {
      if (!dataProps.headerDataSource || dataProps.headerDataSource.length === 0) {
        return message.error("请先添加表头!");
      }
      tagDrawerRef.value?.openDrawer("添加标签", dataProps.dataSource, dataProps.headerDataSource);
    };

    const refreshDataSource = (dataSource: any) => {
      console.log("刷新数据源", dataSource);
      dataProps.dataSource = dataSource;
    };

    const onDeleteHeader = (key: number) => {
      console.log("删除表头", key);
      console.log("dataProps.headerDataSource", dataProps.headerDataSource);
      dataProps.headerDataSource.splice(key, 1);
    };

    const onDeleteTag = (record: any) => {
      console.log("删除标签", record);
      const index = dataProps.dataSource.findIndex((item: any) => item.key === record.key);
      if (index !== -1) {
        dataProps.dataSource.splice(index, 1);
      }
    };

    const onAddAction = (record: any, type: string) => {
      console.log("添加动作", record);
      console.log("type", type);
      if (!videoPlayer.value) {
        return message.error("请先选择视频文件!");
      }
      if (!record[type]) {
        record[type] = [];
      }
      record[type].push(dataProps.currentTime);
    };

    const convertSecondsToTime = (seconds: number) => {
      let hours = Math.floor(seconds / 3600);
      let minutes = Math.floor((seconds % 3600) / 60);
      let secs = Math.floor(seconds % 60); // 确保秒数为整数

      // 时分秒补零
      let pad = (num: number) => String(num).padStart(2, "0");

      let timeString = "";

      if (hours > 0) {
        timeString += `${pad(hours)}时`;
      }
      if (minutes > 0 || hours > 0) {
        // 如果有小时或分钟，才显示分钟部分
        timeString += `${pad(minutes)}分`;
      }
      timeString += `${pad(secs)}秒`;

      return timeString;
    };

    const onDeleteTime = (_record: any, _index: number, key: any, item1: any) => {
      console.log("_record------", _record);
      console.log("_index-----", _index);
      console.log("key-----", key);
      console.log("item1-----", item1);
      _record[key].splice(_index, 1);
    };

    const onForward = (_time: number) => {
      if (!videoPlayer.value) return;
      videoPlayer.value.currentTime = _time;
    };

    const onExport = () => {
      console.log("导出数据====", dataProps.dataSource);
      console.log("dataProps.headerDataSource", dataProps.headerDataSource);
      if (!dataProps.dataSource || dataProps.dataSource.length === 0) {
        return message.error("没有数据可以导出");
      }

      // 创建工作簿
      const wb: XLSX.WorkBook = XLSX.utils.book_new();

      // // 示例数据
      const data = [["标签"]];
      dataProps.headerDataSource.forEach((item: any) => {
        data[0].push(item.title);
      });
      console.log("data", data);
      dataProps.dataSource.forEach((item: any) => {
        const row = [item.title];
        console.log("item", item);
        console.log("row", row);
        let str = "";
        dataProps.headerDataSource.forEach((headerItem: any) => {
          console.log("headerItem", headerItem);
          console.log("item[headerItem.key]", item[headerItem.key]);
          if (item[headerItem.key] && item[headerItem.key]?.length) {
            for (let i = 0; i < item[headerItem.key].length; i++) {
              const element = item[headerItem.key][i];
              str += "【" + convertSecondsToTime(element) + "】\n";
            }
            str += "总计：" + item[headerItem.key].length;
          } else {
            str = "-";
          }
          row.push(str);
        });
        data.push(row);
      });

      // 将数据转换为工作表
      const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(data);

      // 将工作表添加到工作簿中
      XLSX.utils.book_append_sheet(wb, ws, "比赛数据采集" + dayjs().format("YYYY-MM-DD HH:mm:ss"));

      // 导出Excel文件
      XLSX.writeFile(wb, `比赛数据采集${dayjs().format("YYYY-MM-DD HH:mm:ss")}.xlsx`);
    };

    const onCut = (title: string, type: string, item: number) => {
      console.log("onCut===", title);
      console.log("onCut===", type);
      console.log("onCut====", item);
      if (videoPlayer.value) {
        videoPlayer.value.pause();
      }
      videoCutDialogRef.value.openModal(item, `${title}-${type}`, dataProps.videoUrl, dataProps.videoFile);
    };

    const startResize = (e: MouseEvent) => {
      e.preventDefault();
      const startY = e.clientY;
      const startHeight = dataProps.leftHeight;

      const handleMouseMove = (e: MouseEvent) => {
        const deltaY = e.clientY - startY;
        const newHeight = Math.max(200, Math.min(window.innerHeight - 200, startHeight + deltaY));
        dataProps.leftHeight = newHeight;
      };

      const handleMouseUp = () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };

      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    };

    return {
      ...toRefs(dataProps),
      videoPlayer,
      onVideoUpload,
      handlePlay,
      handlePause,
      handelTimeUpdate,
      handleEnded,
      onCreateHeader,
      onCreateTag,
      tagDrawerRef,
      headerDrawerRef,
      refreshDataSource,
      refreshHeaderDataSource,
      onDeleteTag,
      h,
      PlusOutlined,
      onAddAction,
      convertSecondsToTime,
      onDeleteTime,
      onExport,
      onForward,
      onCut,
      videoCutDialogRef,
      onDeleteHeader,
      startResize,
      handleKeyUp,
    };
  },
});
</script>

<style lang="less" scoped>
.page-video-data {
  width: 100%;
  height: 100%;
  gap: 10px;
  background-color: #2f333a;
  padding: 10px;
}

.left-class {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #313234;
  border-radius: 10px;
  box-shadow: 0px 0px 1px #ccc;
  transition: height 0.1s ease;
}

.video-class {
  width: 100%;
  height: 100%;
  background: #313234;
  border-radius: 10px;
  box-shadow: 0px 0px 1px #ccc;
}

.right-class {
  width: 100%;
  background: #313234;
  border-radius: 10px;
  box-shadow: 0px 0px 1px #ccc;
  padding: 10px;
  transition: height 0.1s ease;
}

.custom-file-upload {
  display: inline-block;
  padding: 4px 15px;
  cursor: pointer;
  color: #fff;
  border-radius: 4px;
  background-color: #1677ff;
  display: flex;
  align-items: center;
  font-size: 14px;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
  &:hover {
    background-color: #4096ff;
  }
}

.custom-file-upload input[type="file"] {
  display: none;
}

.table-class {
  :deep(.ant-table-cell) {
    vertical-align: top;
    padding: 2px !important;
    background: #313234 !important;
    color: rgb(178, 178, 178);
  }
  :deep(.ant-table-thead > tr > th) {
    text-align: center;
  }

  :deep(.table-striped) td {
    background-color: #313234;
  }
  :deep(.table-striped) td {
    background-color: rgba(80, 80, 80, 0.1);
  }
  :deep(.ant-empty-description) {
    color: rgb(178, 178, 178);
  }
}

.cell-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #313234;
  padding: 4px 8px;
  border-radius: 10px;
  border: 1px solid;
}

.time-list {
  max-height: 80px;
  overflow: scroll;
  font-size: 10px;
}

.time-item {
  display: flex;
  gap: 4px;
  margin-top: 4px;
  background: #313234;
  border-radius: 4px;
  padding: 0 2px;
  justify-content: space-between;
  color: #fff;
}

.item-icon {
  display: flex;
  gap: 2px;
}

.resizable-divider {
  // margin: 0;
  padding: 4px 0;
  cursor: ns-resize;
  user-select: none;
  &:hover {
    background-color: rgba(22, 119, 255, 0.1);
    color: #fff;
  }
}
</style>
